import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:suxuanapp/http/DioUtil.dart';
import 'package:suxuanapp/http/domain.dart';
/**
 * 参考
 * https://www.it610.com/article/1280448506485555200.htm
 * 官方给开发者提供了js与dart交互的api：
 * https://api.flutter.dev/flutter/dart-js/dart-js-library.html
 */
class NetHomePage extends StatefulWidget {
  NetHomePage({Key key, this.title="网络问题"}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<NetHomePage> {



  void _getData(){
    fetchGet().then((value){
      setState(() {
        //ddddd = value;
        print("数据如下:");
        print(value);
      });
    });
  }
  //返回String, 显示到text文本部件上
  //调用接口 获取服务端数据
  Future<String> fetchGet() async {
    print("准备请求");
    var ma= new Map<String,String>();
    final response =
    await http .get("http://127.0.0.1:4040/get?accessKey=111",headers: {'id':'181','Target_IP':'http://127.0.0.1:3721'} );
    final result = response.body;
    return result;
  }

  void _post(){
    const Target_IP_Port = "Target_IP_Port"; //代理相应错误
    print('------_post--------');
      void getHttp() async {
        try {
          ///发送 FormData:
          FormData formData = FormData.fromMap({"name": "张三", "age": 22});
          var dio = Dio();
          dio.options.headers={'id':'181',Target_IP_Port:'http://127.0.0.1:3721'};
          Response response = await dio.post("http://127.0.0.1:4040/post",  data:formData  );
          print(response.toString()+"具体数据如上");
        } catch (e) {
          print(e);
        }
      }
      getHttp();

  }


  void loadData_sys_post() async {
    print('------loadData_sys_post--------');
    HttpClient httpClient = new HttpClient();
// queryParameters get请求的查询参数(适用于get请求？？？是吗？？？)
// Uri uri = Uri(
//     scheme: "https", host: "app.xxx.com", path: homeRegularListUrl);
// HttpClientRequest request = await httpClient.postUrl(uri);
    var url = 'http://127.0.0.1:4040/getUser';
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

// 设置请求头
    request.headers.set("loginSource", "IOS");
    request.headers.set("useVersion", "3.1.0");
    request.headers.set("isEncoded", "1");
    request.headers.set("bundleId", "com.xxx.xxx");
// Content-Type大小写都ok
    request.headers.set('content-type', 'application/json');
    /// 添加请求体
    /// https://stackoverflow.com/questions/50278258/http-post-with-json-on-body-flutter-dart/50295533
    Map jsonMap = {'currentPage': '1'};
    request.add(utf8.encode(json.encode(jsonMap)));

    HttpClientResponse response = await request.close();
    String responseBody = await response.transform(utf8.decoder).join();
    if (response.statusCode == HttpStatus.ok) {
      print('请求成功');
      print(response.headers);
      print(responseBody);
    }
  }



  void _postJSON() {
//    loadData_sys_post();
    void getHttp() async {
      try {
        var data={'name':"伟大的",'age':88};
        var dio = Dio();
        dio.options.headers={'id':'181','Target_IP':'http://127.0.0.1:3721'};
        Response response = await dio.post("http://127.0.0.1:4040/postJSON",  data:data  );
        print(response.toString()+"具体数据如上");
      } catch (e) {
        print(e);
      }
    }
    getHttp();
  }

  void _getCommpany(){
    Domain.domain.getDomainByCompanyID();
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(child:         Text(
              'get请求',
            ),onPressed: _getData,)
            ,
            RaisedButton(child:         Text(
              'post',
            ),onPressed: _post)
            ,
            RaisedButton(child:         Text(
              'postJSON',
            ),onPressed: _postJSON)
            ,
            RaisedButton(child:         Text(
              '获取企业信息',
            ),onPressed: _getCommpany)




          ],
        ),
      ),
    );
  }
}
